package org.se.scut.hibernate.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;

public class BaseDAO<T> {

	public boolean create(T model)
	{
		Session session = HibernateSessionFactory.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.persist(model);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			return false;
		}
		finally{
			session.close();
		}
		return true;
	}
	
	public boolean update(T model)
	{
		Session session = HibernateSessionFactory.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.merge(model);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			return false;
		}
		finally{
			session.close();
		}
		return true;
	}
	
	public boolean delete(T model)
	{
		Session session = HibernateSessionFactory.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.delete(model);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
			return false;
		}
		finally{
			session.close();
		}
		return true;
	}
	
	
	@SuppressWarnings("unchecked")
	public T find(Class<? extends T> clazz, Serializable id)
	{
		Session session = HibernateSessionFactory.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			return (T)session.get(clazz, id);
		} 
		finally{
			session.getTransaction().commit();
			session.close();
		}
	}
	
	public boolean checkID(Class<? extends T> clazz, Serializable id)
	{
		Session session = HibernateSessionFactory.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.get(clazz, id);
			return true;
		} catch (Exception e) {
			session.getTransaction().rollback();
			return false;
		}
		finally{
			session.getTransaction().commit();
			session.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<T> list(String sql)
	{
		Session session = HibernateSessionFactory.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			return session.createQuery(sql).list();
		}
		finally{
			session.getTransaction().commit();
			session.close();
		}
	}
	
	public boolean deleteByID(Class<? extends T> clazz, int id)
	{
		Session session = HibernateSessionFactory.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			T t = find(clazz, id);
			session.delete(t);
		}catch (Exception e) {
			session.getTransaction().rollback();
			return false;
		}
		finally{
			session.getTransaction().commit();
			session.close();
		}
		return true;
	}
	
}
